# This class is an attempt at an API into Google Project Hosting.
# this maybe should be under api's?  Somehow want both this and the Trac interface to be the same....
# Is this an opportunity to implement webservices to decouple the two sides?



class GoogleProjectHost
 
  def initialize(url)
    @list_url = "#{url}list?can=1"
    @detail_url = "#{url}detail?can=1"
  end 
   
  # return a unique list of all the milestones in the system.
  def list_milestones
     
    milestones = process_issues_page(@list_url) do |ticket_array,parametersHash,structs_to_list|
      milestone = MilestoneStruct.new(:name => ticket_array[parametersHash["Milestone"]])
      if !structs_to_list.include? milestone
        structs_to_list << milestone 
      end
    end
   
    milestones
    
  end
  
  # list all of the tickets associated with a specific milestone.  Adds an extra param so that
  # we filter down a bit what we request from the server.
  def list_tickets(milestone)
    url = build_url("#{@list_url}&q=milestone:#{milestone}")
    tickets = process_issues_page(url) do |ticket_array,parametersHash,structs_to_list|
      user = UserStruct.new(:name => ticket_array[parametersHash["Owner"]])
      if milestone == ticket_array[parametersHash["Milestone"]]
        structs_to_list << TicketStruct.new(
          :ticket_id => ticket_array[parametersHash["ID"]], 
          :name => ticket_array[parametersHash["Summary + Labels"]].gsub("&hellip;","..."),
          :owner => ticket_array[parametersHash["Owner"]],
          :link => "#{@detail_url}?id=#{ticket_array[parametersHash["ID"]]}"
          )
      end
    end
   
    tickets    
  end
  
  # return a unique list of all the users in the system.
  def list_users
    
    users = process_issues_page(@list_url) do |ticket_array,parametersHash,structs_to_list|
      user = UserStruct.new(:name => ticket_array[parametersHash["Owner"]])
      if !structs_to_list.include? user
        structs_to_list << user 
      end
    end
   
    users
    
  end  
  
protected

def build_url(url_to_build)
  url_to_build
end

def process_issues_page(url)
  structs_to_list = []
  
  doc = Hpricot(open(url))
  
  resultstable = doc.search("//table[@id='resultstable']")

  parametersHash = build_parameters_hash(resultstable)
  
  trs = resultstable.search("//tr")
  # skip the first row, it's the header data
  for i in 1...trs.size
    tds = trs[i].search("//td/a")
    ticket_array = tds.collect { |bit| bit.inner_html }
    
    yield ticket_array, parametersHash,structs_to_list
  end

  structs_to_list    
end

  def build_parameters_hash(resultstable)
    parametersHash = {}
    counter = 0
    ths = resultstable.search("//th/a")
    ths.each do |bit|
      parametersHash[bit.inner_html] = counter
      counter += 1
    end
    
    parametersHash
  end
 
end
